"""
@Author: li
@Email: lijianqiao2906@live.com
@FileName: security.py
@DateTime: 2025/07/06
@Docs: 安全相关的工具函数，如密码哈希和JWT令牌处理
"""

from datetime import UTC, datetime, timedelta

from jose import JWTError, jwt
from passlib.context import CryptContext

from app.core.config import settings

#
# --- 密码处理 ---
#
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证明文密码是否与哈希密码匹配"""
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
    """生成密码的哈希值"""
    return pwd_context.hash(password)


#
# --- JWT 令牌处理 ---
#
def create_access_token(subject: str | int, expires_delta: timedelta | None = None) -> tuple[str, int]:
    """创建访问令牌 (Access Token)

    Args:
        subject: 令牌的主题，通常是用户ID
        expires_delta: 令牌的有效期

    Returns:
        一个元组，包含 (令牌字符串, 过期时间戳)
    """
    if expires_delta:
        expire = datetime.now(UTC) + expires_delta
    else:
        expire = datetime.now(UTC) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)

    expire_timestamp = int(expire.timestamp())
    to_encode = {"exp": expire_timestamp, "sub": str(subject)}
    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
    return encoded_jwt, expire_timestamp


def decode_access_token(token: str) -> dict | None:
    """解码访问令牌

    Args:
        token: 令牌字符串

    Returns:
        解码后的令牌负载数据 (payload)，如果解码失败则返回 None
    """
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        return payload
    except JWTError:
        return None
